package problem329;

//329.矩阵中的最长递增路劲
//https://leetcode.cn/problems/longest-increasing-path-in-a-matrix/

class Solution {
    int n,m;
    int[][] dp;
    int[] xx = {1, -1, 0, 0};
    int[] yy = {0,0,1,-1};
    boolean[][] st;
    public int longestIncreasingPath(int[][] matrix) {
        n = matrix.length;
        m = matrix[0].length;
        st = new boolean[n][m];
        dp = new int[n][m];
        int ret = 1;
        for(int i = 0; i<n; i++) {
            for(int j = 0; j<m; j++) {
                st[i][j] = true;
                int x = dfs(matrix, i, j);
                st[i][j] = false;
                ret = Math.max(ret, x);
            }
        }
        return ret;
    }
    public int dfs(int[][] matrix, int x, int y) {
        if(dp[x][y] != 0) return dp[x][y];
        int ret = 1;
        for(int i = 0; i<4; i++) {
            int dx = x + xx[i];
            int dy = y + yy[i];
            if(dx >= 0 && dx < n && dy >= 0 && dy < m && matrix[dx][dy] > matrix[x][y] && !st[dx][dy]) {
                st[dx][dy] = true;
                ret = Math.max(ret, dfs(matrix, dx, dy) + 1);
                st[dx][dy] = false;
            }
        }
        dp[x][y] = ret;
        return ret;
    }
}